package cn.itacst.download;

import org.apache.commons.codec.binary.Base64;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class DownloadServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        System.out.println("DownloadServlet类中的doGet方法执行了");

        //获取请求的文件名, parameter后面有打印
        String parameter = request.getParameter("fileName");
        String fileName = "";

        //serverInfo=Apache Tomcat/7.0.99
        //serverInfo=Apache Tomcat/8.5.88
        String serverInfo = this.getServletContext().getServerInfo();
        System.out.println("serverInfo=" + serverInfo);


        if (serverInfo.contains("Tomcat")) {
            //进来了,说明是tomcat服务器
            String tomcatMainVersion = serverInfo.replace("Apache Tomcat/", "").substring(0, 1);
            if (Integer.parseInt(tomcatMainVersion) >= 8) {
                System.out.println("你当前使用的是tomcat8或以上版本.parameter--- " + parameter);// 此时中文打印的是正确的.如"萌宝宝"
                fileName =parameter;
            } else {
                System.out.println("你当前使用的是tomcat7或以下版本.parameter--- " + parameter);//此时中文打印的是错误的.如"è????????.jpg"
                String iso88591 = "ISO-8859-1";
                String utf8 = "UTF-8";

                String encode = URLEncoder.encode(parameter, iso88591);
                System.out.println("encode="+encode);//encode=%E8%90%8C%E5%AE%9D%E5%AE%9D.jpg
                String decode = URLDecoder.decode(encode, utf8);//decode=萌宝宝.jpg
                System.out.println("decode="+decode);
                //解决中文乱码
                fileName = new String(parameter.getBytes("iso-8859-1"), "utf-8");
            }
        } else {
            System.out.println("您使用的不是tomcat服务器");
            fileName =parameter;
        }

        System.out.println("fileName----" + fileName);

        //加载要被下载的文件数据
        String realPath = getServletContext().getRealPath("/uploadFolder");
        File file = new File(realPath, fileName);
        //通知浏览器以下载的方式请求资源
        //设置响应消息头
        //info.txt  截取点之后的后缀名，
        //设置文件媒体格式
        String mimeType = getServletContext().getMimeType(fileName);
        response.setContentType(mimeType);
        System.out.println("mimeType----" + mimeType);

        //处理中文文件名的乱码问题
        //根据不同的浏览器，不同处理
        String header = request.getHeader("User-Agent");
        // 火狐浏览器 Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:126.0) Gecko/20100101 Firefox/126.0
        // 谷歌浏览器 Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36
        //edge浏览器 Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0
        System.out.println("header---- " + header);
        if (header.toLowerCase().contains("firefox")) {
            System.out.println("您当前使用的是Firefox浏览器");
            //当前是火狐浏览器
            fileName = "=?utf-8?B?" + Base64.encodeBase64String(fileName.getBytes("utf-8")) + "?=";
        } else {
            System.out.println("您当前使用的除Firefox之外的其它浏览器");
            fileName = URLEncoder.encode(fileName, "utf-8");
        }

        System.out.println("fileName-----"+fileName);
        //通知浏览器要被下载的文件的文件名   text/html;charset=utf-8
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        //使用输入流读取数据
        FileInputStream in = new FileInputStream(file);
        ServletOutputStream out = response.getOutputStream();
        //设置一个缓冲区
        byte[] buf = new byte[8192];
        int len = 0;
        while ((len = in.read(buf)) != -1) {
            out.write(buf, 0, len);
            out.flush();
        }
        in.close();
        out.close();

        System.out.println();
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doGet(request, response);
    }

}
